//
//
//  Generated by StarUML(tm) C++ Add-In
//
//  @ Project : OOAD5T
//  @ File Name : MotorController.cpp
//  @ Date : 2026-05-03
//  @ Author : 
//
//
#include "MotorController.h"
#include "SensorController.h"
#include "HDWARE/Motor.h"

MotorController::MotorController(EventBus* bus, Motor& motor)
    : bus(bus), motor(motor), isTurnOn(false) {

    bus->subScribeStartCleaning([this]() {
        this->turnOn();
    });
    bus->subScribeAvoidObstacle([this](SensorProvider* sensor) {
        this->AvoidObstacle(*sensor);
    });
}

void MotorController::turnOn() {
    isTurnOn = true;
    avoiding = false;
}

void MotorController::turnOff() {
    isTurnOn = false;
    avoiding = false;
    mySensor = nullptr;
}

void MotorController::AvoidObstacle(SensorProvider& provider) {
    mySensor = &provider;
    if(isTurnOn == false) {
        return;
	}


    if(provider.getRightState() == false) {
        MCTurnRight();
        avoiding = false;
        bus->publishStartCleaning();
    }else if(provider.getLeftState() == false){
        MCTurnLeft();
        avoiding = false;
        bus->publishStartCleaning();
    }else{
        avoiding = true;
        // No exit yet: next tick should be another backward tick.
    }
}
void MotorController::MCStop() {
    motor.stop();
}

void MotorController::MCMove() {
    if(!avoiding) {
        motor.moveForward();
        return;
    }else{
        if (mySensor != nullptr) {
            motor.moveBackward();
            bus->publishAvoidObstacle(mySensor);
        }
        return;
    }
}

void MotorController::MCTurnLeft() {
    motor.turnLeft();
}

void MotorController::MCTurnRight() {
    motor.turnRight();
}

void MotorController::MCMoveBackward() {
    motor.moveBackward();
}

bool MotorController::isAvoiding() const {
    return avoiding;
}
